//app.js
import request from './utils/request'

App({
  onLaunch: function () {
    // 获取缓存中的login_token
    var that = this
    that.globalData.loginToken = wx.getStorageSync('login_token')
    // 检查微信登陆是否已过期
    wx.checkSession({
      success: function (e) {
        console.log('登录态有效')
        // 如果登录态有效，直接获取用户信息
        that._getUserInfo(that.globalData.loginToken, function (res) { })
      },
      fail: function () {
        console.log('需要重新登录')
        // 登陆态过期，重新获取token，并同步用户信息
        that._login(function (err, res) {
          // 缓存token，用于设置其他请求的header
          if (!err && res.statusCode >= 200 && res.statusCode < 300) {
            // 更新token
            wx.setStorage({
              key: 'login_token',
              data: res.data
            })
            that.globalData.loginToken = res.data
            if (that.loginTokenReadyCallback) {
              that.loginTokenReadyCallback(res)
            }
            let token = res.data
            that._getUserInfo(token, function (res) {})
          }
        })
      }
    })
  },

  /*
   * 微信登陆
   */
  _login: function (callback) {
    let that = this
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId】
        if (res.code) {
          let url = that.globalData.apiHost + '/users/get_wechat_token/'
          wx.request({
            url: url,
            method: 'POST',
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            data: {
              code: res.code
            },
            success: function (res) {
              return callback(null, res)
            }
          })
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
          return callback(res)
        }
      }
    })
  },

  /*
   * 获取用户信息
   */
  _getUserInfo: function (token, callback) {
    let that = this
    wx.getUserInfo({
      success: function (res) {
        console.log(res)
        that.globalData.userInfo = res.userInfo
        if (that.userInfoReadyCallback) {
          that.userInfoReadyCallback(res)
        }
        // 获取用户信息成功，同步信息
        let url = that.globalData.apiHost + '/users/sync_user_info/'
        wx.request({
          url: url,
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded',
            'token': token
          },
          data: {
            raw_data: res.rawData,
            signature: res.signature
          },
          success: function (res) {
            if (res.statusCode >= 200 && res.statusCode < 300) {
              console.log(res.data)
              that.globalData.account = res.data
              if (that.accountReadyCallback) {
                that.accountReadyCallback(res)
              }
              return callback(res)
            } else if (res.statusCode == 400) {
              // 如果在其他手机上打开，需要重新获取token
              that._login(function (err, res) {
                // 缓存token，用于设置其他请求的header
                if (!err && res.statusCode >= 200 && res.statusCode < 300) {
                  // 更新token
                  wx.setStorage({
                    key: 'login_token',
                    data: res.data
                  })
                  that.globalData.loginToken = res.data
                  if (that.loginTokenReadyCallback) {
                    that.loginTokenReadyCallback(res)
                  }
                  that._getUserInfo(res.data, function(res){})
                }
              })
            }
          }
        })
      },
      fail: function (res) {
        // 获取用户信息失败，发送空的同步用户信息请求，用以后台创建空用户
        let url = that.globalData.apiHost + '/users/sync_user_info/'
        wx.request({
          url: url,
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded',
            'token': token
          },
          success: function (res) {
            that.globalData.account = res.data
            if (that.accountReadyCallback) {
              that.accountReadyCallback(res)
            }
            return callback(res)
          }
        })
      }
    })
  },
  _requestUploadToken: function(callback) {
    let that = this
    let url = this.globalData.apiHost + '/albums/get_upload_token/'
    request(url, 'POST', this.globalData.loginToken, {}, function(err, res) {
      console.log(res)
      if (!err) {
        let timestamp = Math.round(new Date().getTime() / 1000)
        that.globalData.upToken = {
          timestamp: timestamp,
          token: res.data
        }
        return callback(null)
      } else {
        return callback(err)
      }
    })
  },

  uploadFormId: function(formId, callback) {
    let that = this
    let params = {
      form_id: formId
    }
    let url = this.globalData.apiHost + '/system/form_id_upload/'
    request(url, 'POST', this.globalData.loginToken, params, function (err, res) {
      console.log(res)
      if (!err) {
        return callback(null)
      } else {
        return callback(err)
      }
    })
  },

  getUploadToken: function(callback) {
    let that = this
    let timestamp = Math.round(new Date().getTime()/1000)
    console.log(this.globalData.upToken)
    // 获取上传token，7000s后失效
    if (this.globalData.upToken) {
      let pastTime = timestamp - this.globalData.upToken.timestamp
      console.log(pastTime)
      if (pastTime > 7000) {
        // 超过7000s，重新获取上传token
        this._requestUploadToken(function (err) {
          if (!err) {
            return callback(null, that.globalData.upToken.token)
          } else {
            return callback(err)
          }
        })
      } else {
        return callback(null, that.globalData.upToken.token)
      }
    } else {
      this._requestUploadToken(function(err) {
        if (!err) {
          return callback(null, that.globalData.upToken.token)
        } else {
          return callback(err)
        }
      })
    }
  },
  globalData: {
    userInfo: null,
    account: null,
    loginToken: null,
    apiHost: 'https://baobei.eqiqu.mobi',
    upToken: null,
    albums: [],
    needRefresh: false
  }
})